#include "BoundingBoxParser.h"

#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

BoundingBoxParser::BoundingBoxParser(
    DoubleParser *&_lowerLeftXParser
    , DoubleParser *&_lowerLeftYParser
    , DoubleParser *&_upperRightXParser
    , DoubleParser *&_upperRightYParser
):    m_lowerLeftXParser(_lowerLeftXParser)
    , m_lowerLeftYParser(_lowerLeftYParser)
    , m_upperRightXParser(_upperRightXParser)
    , m_upperRightYParser(_upperRightYParser)
{

}

bool BoundingBoxParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new BoundingBox());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("lowerLeftX")))
    {
        data = reader->attributes().value(QStringLiteral("lowerLeftX"));
        if (!m_lowerLeftXParser->parse(reader, data))
            return false;
        m_result->lowerLeftX = m_lowerLeftXParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("lowerLeftX: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("lowerLeftY")))
    {
        data = reader->attributes().value(QStringLiteral("lowerLeftY"));
        if (!m_lowerLeftYParser->parse(reader, data))
            return false;
        m_result->lowerLeftY = m_lowerLeftYParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("lowerLeftY: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("upperRightX")))
    {
        data = reader->attributes().value(QStringLiteral("upperRightX"));
        if (!m_upperRightXParser->parse(reader, data))
            return false;
        m_result->upperRightX = m_upperRightXParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("upperRightX: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("upperRightY")))
    {
        data = reader->attributes().value(QStringLiteral("upperRightY"));
        if (!m_upperRightYParser->parse(reader, data))
            return false;
        m_result->upperRightY = m_upperRightYParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("upperRightY: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

BoundingBox *BoundingBoxParser::result()
{
    return m_result.take();
}

}